package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.SRException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    DishService dishService;
    @Autowired
    SetmealService setmealService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> pages(Integer page, Integer pageSize) {
        //创建page对象传入参数
        Page<Category> categoryPage = new Page<>(page,pageSize);
        //排序
        LambdaQueryWrapper<Category> orderByDesc = Wrappers.lambdaQuery(Category.class)
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        //返回参数
       return categoryMapper.selectPage(categoryPage,orderByDesc);
    }

    /**
     * 根据id删除
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //数据库分类表中绑定了菜品和套餐表  需要查询数据库
        //1 需要判断菜品category_id 如果有则不删除
        Integer count1 = dishService.lambdaQuery().eq(Dish::getCategoryId, id).count();
        //判断如果大于0则抛出异常提示用户
        if(count1 > 0){
            throw new SRException("此分类绑定了相应的菜品,不能删除!");
        }
        //2 判断套餐category_id 如果有则不删除
        Integer count2 = setmealService.lambdaQuery().eq(Setmeal::getCategoryId, id).count();
        //判断如果大于0则抛出异常提示用户
        if(count2 > 0){
            throw new SRException("此分类绑定了相应的套餐,不能删除!");
        }
        //3 如果都没有则删除
        this.removeById(id);
    }
}
